//The MIT License (MIT)
//
//Copyright (c) 2018 dote
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of
//this software and associated documentation files (the "Software"), to deal in
//the Software without restriction, including without limitation the rights to
//use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
//the Software, and to permit persons to whom the Software is furnished to do so,
//subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
//FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
//COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
//IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

package com.github.dote.mio.rtt;

public class RTTHandler {
    public static final long RTT_RSTMIN = 2;
    public static final long RTT_RSTMAX = 60;
    private final RTTInfo info;


    public RTTHandler(int defaultAckTimeout) {
        info = new RTTInfo();
        info.setRtt(defaultAckTimeout);
        init();
    }

    public long getRtoMilliseconds() {
        return info.getRtoMilliseconds();
    }

    public void init() {
        info.setRttval(0.75);
        info.setRto(info.getRtt() + (info.getRttval()) * 4);
        info.setTimestamp(System.currentTimeMillis());
    }


    public double minMax(double rto) {
        if (rto > RTT_RSTMAX)
            rto = RTT_RSTMAX;
        else if (rto < RTT_RSTMIN) {
            rto = RTT_RSTMIN;
        }
        return rto;
    }

    public void stop() {
        long stopTimestamp = System.currentTimeMillis() - info.getTimestamp();
        info.setTimestamp(System.currentTimeMillis());
        double delte = 0;
        info.setRtt(stopTimestamp / 1000);
        delte = info.getRtt() - info.getSrtt();
        info.setSrtt(delte / 8);
        info.setRttval(Math.abs(delte) - info.getRttval() / 4);
        info.setRto(minMax(info.getSrtt() + 4 * info.getRttval()));

    }

    public void timeout() {
        info.setRto(minMax(info.getRto() * 2));
        info.setRertyCount(info.getRertyCount() + 1);

    }
}
